<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="公司" prop="company">
        <el-input
          v-model="queryParams.company"
          placeholder="请输入公司"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="部门" prop="departmentName">
        <el-input
          v-model="queryParams.departmentName"
          placeholder="请输入部门"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="姓名" prop="staffName">
        <el-input
          v-model="queryParams.staffName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['module:addressBook:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['module:addressBook:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['module:addressBook:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['module:addressBook:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table v-loading="loading" :data="addressBookList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键ID" align="center" prop="id" />-->
      <el-table-column label="姓名" align="center" prop="staffName" />
      <el-table-column label="部门" align="center" prop="departmentName" />
<!--      <el-table-column label="部门id" align="center" prop="departmentId" />-->
      <el-table-column label="公司" align="center" prop="company" />
<!--      <el-table-column label="岗位id" align="center" prop="postId" />-->
      <el-table-column label="岗位" align="center" prop="postName" />
<!--      <el-table-column label="姓名id" align="center" prop="staffId" />-->
      <el-table-column label="手机号" align="center" prop="phoneNum" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['module:addressBook:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['module:addressBook:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改通讯录页面对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="部门" prop="departmentName">
          <el-cascader
            style="width: 380px"
            v-model="value"
            :options="deptlist"
            :props="optionsProp"
            size="medium "
            placeholder="请输入部门"
            @change="handleChange"></el-cascader>
        </el-form-item>

        <el-form-item label="公司" prop="company">
          <el-input :disabled = "true" v-model="form.company" placeholder="请输入公司" />
        </el-form-item>

        <el-form-item label="岗位" prop="postName">
          <el-select
            @change="changepostinfo"
            v-model="form.postId"
            :multiple="false"
            filterable
            remote
            reserve-keyword
            placeholder="请输入岗位"
            :remote-method="getpostinfolist"
            :loading="loading">
            <el-option
              v-for="item in postinfolist"
              :key="item.id"
              :label="item.postName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="staffName">
          <el-input style="width: 200px" v-model="form.staffName" readonly placeholder="请输入姓名">
            <template slot="append">
              <el-button type="primary" @click="openImportUser2">
                选择员工
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNum">
          <el-input v-model="form.phoneNum" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <Elselect @meiye="myfn" @anme="anmefn" @chongzhi="czfn" @serch="serchfn" @dangqian="dqfn" ref="import" :list="staffList" ></Elselect>
  </div>
</template>

<script>
import { listAddressBook, getAddressBook, delAddressBook, addAddressBook, updateAddressBook } from "@/api/module/addressBook";
import {listDept} from "@/api/system/dept";
import {deptTreeSelect} from "@/api/system/user";
import {listPostInfo} from "@/api/module/postInfo";
import {listStaff} from "@/api/module/staff";
import fujian from "@/components/ImageUpload";
import Elselect from "@/components/ELselect/Elselect";


export default {
  name: "AddressBook",
  components:{
    Elselect
  },
  data() {
    return {
      staffList:[],
      deptList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通讯录页面表格数据
      addressBookList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        departmentName: null,
        departmentId: null,
        company: null,
        postId: null,
        postName: null,
        staffName: null,
        staffId: null,
        phoneNum: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        staffName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        phoneNum: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
        departmentName: [
          { required: true, message: "部门不能为空", trigger: "blur" }
        ],
        postName: [
          { required: true, message: "岗位不能为空", trigger: "blur" }
        ],
        company: [
          { required: true, message: "公司不能为空", trigger: "blur" }
        ],
      },
      deptlist:[],
      optionsProp:{value:'id',label:'label',children:'children'},
      value:[],
      postinfolist:[],//岗位
    };
  },
  created() {
    this.getList();
    this.getdeptlist()//部门
    this.getList();
    this.getpostinfolist()//岗位
  },
  methods: {
    //获取部门列表
    async getdeptlist(){
      let res=await deptTreeSelect()
      this.deptlist=res.data
    },
    handleChange(value){
      /*  this.form.company*/
      this.form.departmentId=value[2]
      this.getlcompany(this.deptlist,value[1],this.form.company)
      this.getdeptlabel(this.deptlist,value[2],this.form.company)
    },
    //遍历数组
    getlcompany(arr,value,label){
      var newlabel=''
      for(var i=0;i<arr.length;i++){
        if(arr[i].id==value){
          newlabel=arr[i].label
          this.form.company=arr[i].label
        }
        if(arr[i].children){
          this.getlcompany(arr[i].children,value,label)
        }
      }
    },
    getdeptlabel(arr,value,label){
      arr.forEach(item=>{
        if(item.id==value){
          label=item.label
          this.form.departmentName=item.label
          return
        }
        if(item.children){
          this.getdeptlabel(item.children,value,label)
        }
      })
    },
    //获取岗位
    getpostinfolist(query){
      listPostInfo({postName:query}).then(res=>{
        this.postinfolist=res.rows
      })

    },
    changepostinfo(val){
      this.form.postId=val
      this.postinfolist.forEach(item=>{
        if(item.id==val){
          this.form.postName=item.postName
        }
      })

    },
    //组件
    openImportUser2() {
      this.$refs.import.show();
    },
    async myfn(val){
      console.log(val)
      this.queryParams.pageSize=val
      const res = await listStaff(this.queryParams)
      // console.log(res.rows)
      this.staffList=res.rows
    },
    async dqfn(val){
      this.queryParams.pageNum=val
      const res = await listStaff(this.queryParams)
      // console.log(res.rows)
      this.staffList=res.rows
    },
    //组件搜索功能
    async serchfn(val){
      this.queryParams.name=val
      const res = await listStaff(this.queryParams)
      this.staffList=res.rows
    },
    //组件重置功能
    async czfn(){
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        username: null,
        trainingItems: null,
        sponsor: null,
        sponsorDept: null,
        participant: null,
        participantDept: null,
        initiateTime: null,
        startTime: null,
        endTime: null,
        days: null,
        status: null,
        tenantId: null,
        staffId: null,
        staffName: null,
      }
      const res = await listStaff(this.queryParams)
      this.staffList=res.rows
      this.listDatafn()
    },
    anmefn(val){
      this.form.staffName=val.name
      this.form.staffId=val.id
      this.$refs.import.visible=false
    },
    handleNodeClick(data) {
      console.log(data);
      this.form.departmentId = data.label
      console.log(data);
    },
    /** 查询通讯录页面列表 */
    getList() {
      this.loading = true;
      listAddressBook(this.queryParams).then(response => {
        this.addressBookList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();

    },
    // 表单重置
    reset() {
      this.value=[]
      this.form = {
        id: null,
        departmentName: null,
        departmentId: null,
        company: null,
        postId: null,
        postName: null,
        staffName: null,
        staffId: null,
        phoneNum: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      this.open = true;
      listDept(this.queryParams).then(response => {
        this.deptList = this.normalizer(response.data)
        this.loading = false;
      });
      this.title = "添加通讯录页面";
      const res = await listStaff(this.queryParams);
      this.staffList = res.rows;
      this.$refs.import.unit = res.total;
    },
    /** 转换部门数据结构 */
    normalizer(item) {
      console.log(item)
       item.forEach((node)=>{
          node.id=node.departmentId,
          node.label=node.departmentName,
          node.children= node.children
       })
      console.log(item)
      return item

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAddressBook(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.value=[100]
        this.getcomponylist(this.form.company,this.deptlist)
        this.value.push(this.form.departmentId)
        this.title = "修改通讯录页面";
      });
    },
    // 处理回显数据
    getcomponylist(val,arry){
      arry.forEach(item=>{
        if(item.label==val){
          this.value.push(Number(item.id))
          return
        }
        if(item.children){
          this.getcomponylist(val,item.children)
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAddressBook(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAddressBook(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除通讯录页面编号为"' + ids + '"的数据项？').then(function() {
        return delAddressBook(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('module/addressBook/export', {
        ...this.queryParams
      }, `addressBook_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
